package app.hanxiao.com.demo.push.Factory;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

public class MyTextLineEnCode implements ProtocolEncoder {
	private String codeFormat_GB2312 = "GB2312";
	private String codeFormat_UTF = "GB2312";
	@Override
	public void dispose(IoSession arg0) throws Exception {
		
		
	}

	@Override
	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
		String s = null;
		if (message instanceof String) {
			s = (String) message;
		}
		if (s != null) {
			Charset cs = Charset.forName(codeFormat_UTF);
			CharsetEncoder charsetEncoder =(CharsetEncoder)session.getAttribute("GB2312");
			if (charsetEncoder == null) {
				charsetEncoder = cs.newEncoder(); 
				session.setAttribute(codeFormat_UTF,charsetEncoder);
			}
			//开辟内存小大
			IoBuffer ioBuffer = IoBuffer.allocate(s.length());
			//设置自动选择内存大小
			ioBuffer.setAutoExpand(true);
			ioBuffer.putString(s, charsetEncoder);
			ioBuffer.flip();
			out.write(ioBuffer);
		}

	}

}
